import exceed from 'utils/apimap';
import utils, { NameSpace } from 'utils';
import { Dialog, Tag } from '@teamix/ui';
import intl from '../../../locale';

const ns = NameSpace('upgradeProjectRepos');

export const UPDATE_DATA = ns('UPDATE_DATA');
export const RECEIVE_REPO_SETTING = ns('RECEIVE_REPO_SETTING');

// 获取最近第一次的记录
export const defaultLastRecordPage = {
  CREATED: 1,
  UNKNOWN_FAILED: 1,
  SUCCESS: 1,
};

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

function handleRes(res) {
  return {
    total: res[0].amount,
    list: res.slice(1),
  };
}

// customizeStep自定义step，step是否自定义，用于切换企业时到第二个步骤
export function getLastRecord(lastRecordCurPage = defaultLastRecordPage, customizeStep = false) {
  return (dispatch) => {
    if (customizeStep) {
      return;
    }

    // const { curStep } = getState();
    // 根据三种状态判断进度;
    const lastAllPromise = ['PROCESSING', 'CREATED', 'UNKNOWN_FAILED', 'SUCCESS'].map((item) => {
      return new Promise((resolve, reject) => {
        exceed
          .fetch({
            api: 'upgrade.records.last',
            data: {
              status: item,
              page: lastRecordCurPage[item],
              per_page: 8,
              order_by: '',
              sort: '',
            },
          })
          .then((result) => {
            resolve(result);
          })
          .fail((err) => {
            reject(err);
          });
      });
    });

    Promise.all(lastAllPromise)
      .then((res) => {
        const [createdRes, processRes, failRes, successRes] = res;
        const { list: failList, total: failTotal } = handleRes(failRes);
        const { list: successList, total: successTotal } = handleRes(successRes);
        const { list: processList, total: processTotal } = handleRes(processRes);
        const { list: createdList, total: createdTotal } = handleRes(createdRes);
        const curCreatedList = [...createdList, ...processList];
        const curCreatedTotal = processTotal + createdTotal;

        // 没有数据则为从未导入
        if (curCreatedTotal === 0 && successTotal === 0 && failTotal === 0) {
          updateData({
            curStep: 0,
            isLoadingProgress: false,
          })(dispatch);
          return;
        }

        updateData({
          curStep: 3,
          isLoadingProgress: false,
          lastRecord: {
            CREATED: {
              list: curCreatedList,
              pageInfo: {
                total: curCreatedTotal,
                pageSize: 8,
                currentPage: lastRecordCurPage.CREATED,
              },
            },

            UNKNOWN_FAILED: {
              list: failList,
              pageInfo: {
                total: failTotal,
                pageSize: 8,
                currentPage: lastRecordCurPage.UNKNOWN_FAILED,
              },
            },

            SUCCESS: {
              list: successList,
              pageInfo: {
                total: successTotal,
                pageSize: 8,
                currentPage: lastRecordCurPage.SUCCESS,
              },
            },
          },

          lastUpgradeLoaded: true,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
        updateData({
          lastUpgradeLoaded: true,
          isLoadingProgress: false,
        })(dispatch);
      });
  };
}

// 获取企业列表
export function getOrganizations() {
  return (dispatch) => {
    updateData({
      isLoadingOrg: true,
    })(dispatch);
    const getOrgPromise = new Promise((resolve, reject) => {
      exceed
        .fetch({
          api: 'organization.list',
        })
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });

    getOrgPromise
      .then((res) => {
        const { organization = {} } = window.FORCE || {};
        const list = res.slice(1);
        const index = list.findIndex(
          (item) => item.organization_id === organization.organization_id,
        );
        // 有权限则设置默认值
        updateData({
          selectedOrganizationId: index > -1 ? organization.organization_id : '',
          organizations: list,
          isLoadingOrg: false,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
        updateData({
          isLoadingOrg: false,
        })(dispatch);
      });
  };
}

// 切换企业后刷新页面
export function switchOrganizations() {
  return (dispatch, getState) => {
    const { selectedOrganizationId } = getState();
    updateData({
      isGoStep1: true,
    })(dispatch);
    const getOrgPromise = new Promise((resolve, reject) => {
      exceed
        .fetch({
          api: 'organization.switch',
          data: {
            organization_id: selectedOrganizationId,
          },
        })
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });

    getOrgPromise
      .then(() => {
        updateData({
          isGoStep1: false,
        })(dispatch);
        window.location.href = `${window.location.origin}${window.location.pathname}?step=1&switch_org=true&org_id=${selectedOrganizationId}`;
      })
      .catch((err) => {
        console.error(err);
        updateData({
          isGoStep1: false,
        })(dispatch);
      });
  };
}

// 查询Code阿里云可升级代码库列表
export function getProjects(page = 1, search = undefined) {
  return (dispatch, getState) => {
    let searchKey;
    const { setp1Search, step1Pagination, allPageProjects } = getState();

    if (search) {
      searchKey = search;
    } else {
      searchKey = setp1Search;
    }

    updateData({
      isLoadingProjects: true,
    })(dispatch);

    // 解析cookie
    const aliyun_pk =
      utils.parseCookie(document.cookie).login_aliyunid_pk ||
      utils.parseCookie(document.cookie).yunpk ||
      '';

    const getProjectsPromise = new Promise((resolve, reject) => {
      exceed
        .fetch({
          api: 'upgrade.projects.get',
          data: {
            page,
            per_page: step1Pagination.pageSize,
            order_by: '',
            sort: '',
            search: searchKey,
            aliyun_pk,
          },
        })
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });

    getProjectsPromise
      .then((res) => {
        const list = res.slice(1);
        list.forEach((item) => {
          const index = allPageProjects.findIndex(
            (item2) => item2.original_project_id === item.original_project_id,
          );
          if (index === -1) {
            allPageProjects.push(item);
          }
        });
        updateData({
          allProjects: res.slice(1),
          allPageProjects,
          step1Pagination: {
            ...step1Pagination,
            currentPage: page,
            total: res[0].amount,
          },

          isLoadingProjects: false,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
        updateData({
          isLoadingProjects: false,
        });
      });
  };
}

// 提交升级任务
export function postProjects(projects) {
  return (dispatch, getState) => {
    const { sync_member } = getState();
    updateData({
      isUpgrading: true,
    })(dispatch);

    const aliyun_pk =
      utils.parseCookie(document.cookie).login_aliyunid_pk ||
      utils.parseCookie(document.cookie).yunpk ||
      '';

    const postProjectsPromise = new Promise((resolve, reject) => {
      exceed
        .fetch({
          api: 'upgrade.projects.post',
          data: {
            projects,
            sync_member,
            aliyun_pk,
          },
        })
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });

    postProjectsPromise
      .then((result) => {
        const { submit_fail_projects, submit_success_projects } = result;
        if (submit_fail_projects.length) {
          updateData({
            isUpgrading: false,
          })(dispatch);
          Dialog.confirm({
            messageProps: {
              type: 'notice',
            },
            title: intl.get({
              id: 'code-assets.code-aliyun-upgrade.actions.UpgradeReminder',
              defaultMessage: '升级提醒',
            }),
            content: (
              <div className="upgrade-step2-notice-content">
                <div className="upgrade-step2-notice-content-desc">
                  {intl.get({
                    id: 'code-assets.code-aliyun-upgrade.actions.TheFollowingItemsHaveBeen',
                    defaultMessage: '以下项目已被管理员执行升级，将自动跳过。',
                  })}
                </div>
                <div>
                  {submit_fail_projects.map((item) => {
                    return (
                      <span className="upgrade-step2-notice-content-tag">
                        <Tag>{item.original_repo_path}</Tag>
                      </span>
                    );
                  })}
                </div>
                {submit_success_projects.length ? null : (
                  <div className="upgrade-step2-notice-content-tip">
                    {intl.get({
                      id: 'code-assets.code-aliyun-upgrade.actions.NoProjectsCanBeUpgraded',
                      defaultMessage: '暂无可以升级的项目，请重新选择',
                    })}
                  </div>
                )}
              </div>
            ),

            okProps: {
              children: intl.get({
                id: 'code-assets.code-aliyun-upgrade.actions.ISee',
                defaultMessage: '我知道了',
              }),
            },
            onOk: () => {
              if (submit_success_projects.length) {
                updateData({
                  // 去当前升级列表
                  curStep: 3,
                  // 标识页面来源
                  isLoadingProgress: true,
                })(dispatch);
                dispatch(getLastRecord());
              } else {
                updateData({
                  curStep: 1,
                })(dispatch);
              }
            },
            footerActions: ['ok'],
          });
        } else {
          updateData({
            isUpgrading: false,
            // 去当前升级列表
            curStep: 3,
            isLoadingProgress: true,
          })(dispatch);
          dispatch(getLastRecord());
        }
      })
      .catch((err) => {
        console.error(err);
        updateData({
          isUpgrading: false,
        });
      });
  };
}

// 获取所有已升级项目
export function getAllRecords({ page = 1, search = '' }) {
  return (dispatch, getState) => {
    const { allRecordsPagination } = getState();
    updateData({
      isLoadingAllRecords: true,
    })(dispatch);

    const postProjectsPromise = new Promise((resolve, reject) => {
      exceed
        .fetch({
          api: 'upgrade.records.all',
          data: {
            status: 'SUCCESS',
            page,
            per_page: 8,
            order_by: '',
            sort: '',
            search,
          },
        })
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });

    postProjectsPromise
      .then((res) => {
        updateData({
          isLoadingAllRecords: false,
          allRecords: res.slice(1),
          allRecordsPagination: {
            ...allRecordsPagination,
            total: res[0].amount,
            currentPage: page,
          },
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
        updateData({
          isLoadingAllRecords: false,
        });
      });
  };
}

// 查询企业设置
export function getOrgSetting() {
  return (dispatch) => {
    const org_id = (window.FORCE.organization && window.FORCE.organization.id) || '';
    const repoPromise = new Promise((resolve) => {
      exceed
        .forceFetch({
          api: 'organization.repo.setting.get',
          params: {
            org_id,
          },
        })
        .then((result) => {
          resolve(result);
        });
    });
    const groupPromise = new Promise((resolve) => {
      exceed
        .forceFetch({
          api: 'organization.group.setting.get',
          params: {
            org_id,
          },
        })
        .then((result) => {
          resolve(result);
        });
    });
    Promise.all([groupPromise, repoPromise])
      .then((res) => {
        const [groupSetting, repoSetting] = res;
        updateData({
          groupVisibility: groupSetting.group_visibility_level,
          repoVisibility: repoSetting.repo_visibility_level,
          orgSettingLoaded: true,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
      });
  };
}
